package com.matu.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.parser.ParseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.matu.domain.Ligne;
import com.matu.service.ServiceTisseo;
import com.matu.util.DBManager;


@Controller
public class LikeController {
		@SuppressWarnings("unused")
		private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
		
		/**
		 * Simply selects the home view to render by returning its name.
		 */
		@RequestMapping(value = "/addLike", method = RequestMethod.GET)
		public String addLike(Locale locale, Model model, HttpServletRequest request,HttpServletResponse response) {
			
			ServiceTisseo sTisseo = new ServiceTisseo();
			
			/*
			 * Chercher les lignes
			 */
			ArrayList<Ligne> listeDesLignes = new ArrayList<Ligne>();
			try {
				listeDesLignes = sTisseo.getServiceListeLignes();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			
			model.addAttribute("listLigne", listeDesLignes);
			
			
			/*
			 * Gestion des likes
			 */
			
			String idSelectedLigne = (String) request.getParameter("idLigne");
			String like = (String) request.getParameter("like");
			String userid = (String) request.getSession().getAttribute("userid");
			
			DBManager toto = new DBManager();
			toto.updateLike(userid, like, idSelectedLigne, listeDesLignes);
			
			
			
			
			/*
			 * Redirection
			 */
			String page = request.getHeader("Referer");
			
			try {
	
				response.sendRedirect(page);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			
			return "addLike";
		}

}
